import java.net.*;
import java.io.*;
import java.applet.*;

import com.sun.j3d.utils.applet.MainFrame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;


public class Client implements Runnable{
	String ipAdd;
	int destPort = 13161;
	int srcPort = 13160;
	public TextField msgTF = new TextField();  
	public String name;
	public Applet applet;
	public DatagramSocket mySocket;
	
	public Client(Applet a,String n,String ip){
		System.out.println("Client:");
		applet = a;
		ipAdd  = ip;
		name = n;
	}
	
	public void run(){
		showGui();
		connect();
		new Thread(new Receiver(this)).run();
	}
	
	public void connect(){
		try{
			mySocket = new DatagramSocket(srcPort);
		}catch(Exception e){System.out.println(e);}
		
		if(mySocket==null) { showMsg("Could not create Socket"); return; }
	}
	
	public void showGui(){
		applet.add(new Label("Client1:"));
		applet.add(new Label("IP-Addr: " + ipAdd));
		msgTF.setColumns(10);
		applet.add(msgTF);
		Button sendButton = new Button("senden");
		
		ActionListener sendAction = new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				String msg = msgTF.getText();
				if(msg.length() != 0) if(msg.charAt(0) != ' '){
					System.out.println("Sent: " + msg);
					send(msg);
				}
			}};
		sendButton.addActionListener(sendAction);
		applet.add(sendButton);
		//Darstellung aktualisieren
		applet.doLayout();
	}
	
	public void send(String msg){
		if(mySocket==null) { showMsg("Not Connected - trying to connect..."); connect(); return; }
		try { 
			DatagramPacket p = new DatagramPacket(msg.getBytes(),msg.getBytes().length,InetAddress.getByName(ipAdd),destPort);
			mySocket.send(p);
		}catch (IOException ioe) {System.out.println( ioe );} 
	}
	
	public void showMsg(String msg){
		applet.add(new Label(msg));
		//Darstellung aktualisieren
		applet.doLayout();
	}
	

}